package org.chen.translate.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Getter;
import lombok.Setter;
import org.chen.common.translate.dto.TranslateRequestDTO;
import org.chen.common.translate.result.ResultVO;
import org.chen.translate.service.TencentTranslateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.tmt.v20180321.models.TextTranslateResponse;

@RestController
@RequestMapping("/translate")
public class TencentTranslateController {
    
    @Autowired
    private TencentTranslateService translateService;

    /**
     * 完整翻译接口
     * @param request 翻译请求参数
     * @return 翻译结果
     */
    @PostMapping("/text")
    @Tag(name = "腾讯云翻译接口", description = "腾讯云翻译相关接口")
    public ResultVO translateText(@RequestBody TranslateRequestDTO request) {
        long startTime = System.currentTimeMillis();

        try {
            // 基本参数验证
            if (request.getSourceText() == null || request.getSourceText().trim().isEmpty()) {
                return ResultVO.fail("源文本不能为空");
            }
            if (request.getSource() == null || request.getTarget() == null) {
                return ResultVO.fail("源语言和目标语言不能为空");
            }

            // 检查文本长度
            if (request.getSourceText().length() > 5000) {
                return ResultVO.fail("文本长度不能超过5000字符");
            }

            TextTranslateResponse response = translateService.translateText(request);

            long duration = System.currentTimeMillis() - startTime;

            // 封装返回结果，包含耗时信息
            TranslateResult result = new TranslateResult();
            result.setSourceText(request.getSourceText());
            result.setTargetText(response.getTargetText());
            result.setSource(request.getSource());
            result.setTarget(request.getTarget());
            result.setDuration(duration);
            result.setRequestId(response.getRequestId());

            return ResultVO.success(result);

        } catch (TencentCloudSDKException e) {
            long duration = System.currentTimeMillis() - startTime;

            // 处理特定的腾讯云错误
            String errorMessage = handleTencentCloudError(e);

            return ResultVO.fail(String.format("翻译失败（耗时%dms）：%s", duration, errorMessage));

        } catch (Exception e) {
            long duration = System.currentTimeMillis() - startTime;
            return ResultVO.fail(String.format("系统错误（耗时%dms）：%s", duration, e.getMessage()));
        }
    }

    /**
     * 限流状态查询接口
     */
    @GetMapping("/status")
    @Tag(name = "查询限流状态")
    @Operation(summary = "查询腾讯翻译限流状态", description = "查询当前腾讯翻译服务的限流状态")
    public ResultVO getRateLimitStatus() {
        try {
            String status = translateService.getRateLimitStatus();
            return ResultVO.success(status);
        } catch (Exception e) {
            return ResultVO.fail("查询状态失败：" + e.getMessage());
        }
    }

    /**
     * 重置限流器接口（管理员使用）
     */
    @PostMapping("/reset-limiter")
    @Tag(name = "重置限流器", description = "紧急情况下重置限流器")
    @Operation(summary = "重置腾讯翻译限流器", description = "紧急情况下重置腾讯翻译限流器")
    public ResultVO resetRateLimiter() {
        try {
            translateService.resetRateLimiter();
            return ResultVO.success("限流器已重置");
        } catch (Exception e) {
            return ResultVO.fail("重置限流器失败：" + e.getMessage());
        }
    }

    /**
     * 处理腾讯云特定错误
     */
    private String handleTencentCloudError(TencentCloudSDKException e) {
        String message = e.getMessage();
        if (message == null) return "未知错误";

        if (message.contains("frequency limit") || message.contains("rate limit")) {
            return "请求过于频繁，已自动重试但仍失败，请稍后再试";
        } else if (message.contains("InvalidParameter")) {
            return "参数错误，请检查源语言、目标语言和文本内容";
        } else if (message.contains("AuthFailure")) {
            return "认证失败，请检查腾讯云密钥配置";
        } else if (message.contains("UnsupportedOperation")) {
            return "不支持的操作或语言对";
        } else {
            return message;
        }
    }

    // 内部类定义
    @Setter
    @Getter
    public static class TranslateResult {
        // Getters and Setters
        private String sourceText;
        private String targetText;
        private String source;
        private String target;
        private long duration;
        private String requestId;
        private int index;
        private boolean success = true;
        private String errorMessage;

    }
}